﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Windows.Forms;

namespace WindowsFormsApplication2
{
    public class my58Login:BoundaryPostData
    {
        public my58Login(CookieCollection cklist)
            : base(cklist)
        {



        }


        public string StartLogin(string username, string pwd)
        {
            string newstroldvipss = doreqoutget(false, "http://passport.58.com/login", "");
            string newstroldid58 = doreqoutget(false, "http://tracklog.58.com/referrer4.js", "");
            //  string newstroldidwxtk = doreqoutget(false, "http://passport.58.com/wxqrcode?temp=1ighbg53s", "");

            string url2 = "http://passport.58.com/login";
            var a = "";

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url2);
            req.Method = "GET";
            WebProxy wp = new WebProxy("121.40.195.200:808");

            //  req.Proxy = wp;
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            //    WebHeaderCollection responseHeaders = res.Headers;

            //if (keepContext)
            //{
            //    context.Cookies = res.Cookies;
            //    context.Referer = _requestUrl;
            //}
            using (Stream stream = res.GetResponseStream())
            {
                using (StreamReader streamReader = new StreamReader(stream))
                {
                    string msg = streamReader.ReadToEnd();
                    a = msg;
                    int ac = res.Cookies.Count;
                    if (ac > 0)
                    {


                        cklist.Add(res.Cookies);
                    }
                }
            }
            string aout = getlt(a);
            string ptk = getptk(a);

            string cd = getcd(a);
            string pathpt = " name=\"path\" value=\"([^\"]+)\"";
            string path = HttpUtility.UrlEncode(getBysrcAndpattern(a, pathpt));
            var ts = "1411093330885";
            string c1 = File.ReadAllText(Application.StartupPath + "\\58code2.js");
            string c2 = File.ReadAllText(Application.StartupPath + "\\58code3.js");
            var p1 = ExecuteScript("getm32str('"+pwd+"','" + ts + "')", c1);
            var p2 = ExecuteScript("getm16str('"+pwd+"','" + ts + "')", c1);

            var p3 = ExecuteScript("encryptString('" + ts + pwd + "','010001','" + aout + "')", c2);
            string ov = @"isweak=0&path=" + path + "&p1=" + p1 + "&p2=" + p2 + "&p3=" + p3 + "&timesign=" + ts + "&ptk=" + ptk + "&cd=" + cd + "&username="+username+"&password=&source=pc-login&mrisktype=1&pptmobilecodeloginmobile=%E8%AF%B7%E8%BE%93%E5%85%A5%E6%89%8B%E6%9C%BA%E5%8F%B7&pptmobilecodeloginmobilecode=&mcresult=undefined";

            string urldo = "http://passport.58.com/dounionlogin";
            Cookie ca = new Cookie();

            ca.Name = "als";
            ca.Value = "0";

            ca.Domain = "58.com";
            cklist.Add(ca);
            ca = new Cookie();

            ca.Name = "new_session";
            ca.Value = "1";

            ca.Domain = "58.com";
            cklist.Add(ca);
            ca = new Cookie();

            ca.Name = "new_uv";
            ca.Value = "1";

            ca.Domain = "58.com";
            cklist.Add(ca);
            ca = new Cookie();

            ca.Name = "undefined";
            ca.Value = "758bf51d-0254-4561-889d-965442a44f4e";

            ca.Domain = "58.com";
            // cklist.Add(ca);
            ca.Name = "f";
            ca.Value = "n";

            ca.Domain = "58.com";
            cklist.Add(ca);
            // cklist.Add(new Cookie("als","0"));
            //cklist.Add(new Cookie("new_session", "1","58.com"));
            //cklist.Add(new Cookie("new_uv", "1", "58.com"));
            //cklist.Add(new Cookie("undefined", "758bf51d-0254-4561-889d-965442a44f4e", "58.com"));
            string doout = doreqout(false, urldo, ov);
            //  string my58 = getBysrcAndpattern(doout, "window.parent.location=\"([^\"]+)\";");
            //   string doout2 = doreqout(false, urldo, ov);
            //  string ur3=getBysrcAndpattern(a, pathpt);
            //string newstr = doreqoutget(true, "http://my.58.com/", "");
            //int ab = 0;


            return doout;
        }

        private static string getlt(string msg)
        {
            string pt = "\"010001\", \"([^\"]+)\"";

            var match2 = Regex.Match(msg, pt);
            string rich2 = match2.Groups[1].Value;
            return rich2;

        }
        private static string getptk(string msg)
        {
            string pt = " id=\"ptk\" value=\"([^\"]+)\"";

            var match2 = Regex.Match(msg, pt);
            string rich2 = match2.Groups[1].Value;
            return rich2;
        }



        private static string getcd(string msg)
        {
            string pt = " id=\"cd\" value=\"([^\"]+)\"";

            var match2 = Regex.Match(msg, pt);
            string rich2 = match2.Groups[1].Value;
            return rich2;
        }
        public string doreqout(bool allowdir, string urla, string postdata)
        {

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(urla);

            req.CookieContainer = new CookieContainer();


            req.CookieContainer.Add(cklist);

            req.Method = "POST";
            WebProxy wp = new WebProxy("121.40.195.200:808");

            //req.Proxy = wp;
            req.AllowAutoRedirect = allowdir;
            byte[] bs = Encoding.ASCII.GetBytes(postdata);
            string responseData = String.Empty;
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = bs.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(bs, 0, bs.Length);
                reqStream.Close();
            }

            CookieCollection ckl = new CookieCollection();
            HttpWebResponse res = (HttpWebResponse)req.GetResponse();
            if (res.Headers.AllKeys.Contains("Set-Cookie"))
            {

                string mheader = res.Headers["Set-Cookie"].ToString();
                   ckl = strCokAddCol1(mheader, "58.com");

                if (ckl.Count > 0)
                {

                    this.LastStatus = "登陆成功";
                }
                else
                {
                    this.LastStatus = "登陆失败";

                }
            }
            else
            {
                this.LastStatus = "登陆失败";

            }
            //    WebHeaderCollection responseHeaders = res.Headers;

            //if (keepContext)
            //{
            //    context.Cookies = res.Cookies;
            //    context.Referer = _requestUrl;
            //}
            cklist.Add(ckl);
            using (Stream stream = res.GetResponseStream())
            {
                using (StreamReader streamReader = new StreamReader(stream))
                {
                    string msg = streamReader.ReadToEnd();

                    int a = res.Cookies.Count;
                    if (a > 0)
                    {


                        cklist.Add(res.Cookies);
                    }
                    //    string lc = res.Headers["Location"].ToString();
                    return msg;
                }
            }

            return "";

        }

        public static CookieCollection strCokAddCol1(string s, string defaultDomain)
        {
            CookieCollection cc = new CookieCollection();
            if (string.IsNullOrEmpty(s) || s.Length < 5 || s.IndexOf("=") < 0) return cc;
            if (string.IsNullOrEmpty(defaultDomain) || defaultDomain.Length < 5) return cc;
            s.TrimEnd(new char[] { ';' }).Trim();

            //用软件截取的cookie会带有expires，要把它替换掉【isGood代码】
            if (s.IndexOf("expires=") >= 0)
            {
                s = replace(s, @"expires=[\w\s,-:]*GMT[;]?", "");
            }
            //只有一个cookie直接添加【isGood代码】
            if (s.IndexOf(";") < 0)
            {
                System.Net.Cookie c = new System.Net.Cookie(s.Substring(0, s.IndexOf("=")), s.Substring(s.IndexOf("=") + 1));
                c.Domain = defaultDomain;
                cc.Add(c);
                return cc;
            }
            //不同站点与不同路径一般是以英文道号分别【isGood代码】
            if (s.IndexOf(",") > 0)
            {
                s.TrimEnd(new char[] { ',' }).Trim();
                foreach (string s2 in s.Split(','))
                {
                    cc = strCokAddCol(s2, defaultDomain, cc);
                }
                return cc;
            }
            return cc;
        }

        private static CookieCollection strCokAddCol(string s, string defaultDomain, CookieCollection cc)
        {
            try
            {
                s.TrimEnd(new char[] { ';' }).Trim();
                System.Collections.Hashtable hs = new System.Collections.Hashtable();

                string sa = s.Split(';')[0];






                Cookie c = new Cookie();
                c.Name = Regex.Replace(sa.Substring(0, sa.IndexOf('=')), @"\r\n", "").ToString();
                c.Value = Regex.Replace(sa.Substring(sa.IndexOf('=') + 1), @"\r\n", "").ToString();

                c.Domain = defaultDomain;
                cc.Add(c);

            }
            catch (Exception e)
            {

            }
            return cc;
        }

        public static string replace(string strSource, string strRegex, string strReplace)
        {
            try
            {
                Regex r;
                r = new Regex(strRegex, RegexOptions.IgnoreCase | RegexOptions.Singleline);
                string s = r.Replace(strSource, strReplace);
                return s;
            }
            catch
            {
                return strSource;
            }
        }
    }
}